<!--
 * @Description: 
 * @Author: ldx
 * @Date: 2023-03-02 21:05:41
 * @LastEditors: ldx
 * @LastEditTime: 2023-03-22 23:15:21
-->
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    body {
      margin: 0;
      overflow: hidden;
    }
  </style>
</head>

<body>
  <script id="vertex" type="x-shader/x-vertex">
    attribute vec4 a_Position;
    void main(){
      // 顶点位置
      gl_Position = a_Position;
      // 顶点大小
      gl_PointSize = 20.0;
    }
  </script>
  <script id="fragment" type="x-shader/x-fragment">
    void main(){
      // 片元颜色
      gl_FragColor = vec4(1,0,0,1);
    }
  </script>
  <canvas id="canvas"></canvas>
  <script type="module">
    import { initProgram, getMousePosInWebgl } from '../jsm/utils.js'
    import Poly from '../jsm/Poly.js'
    const canvas = document.querySelector('#canvas')
    // 设置canvas容器的宽高
    canvas.width = window.innerWidth
    canvas.height = window.innerHeight
    // 获取webgl上下文
    const gl = canvas.getContext('webgl');
    // 声明将来用来清空绘图区的颜色。分别对应r,g,b,a
    gl.clearColor(0, 0, 0, 1)
    // 使用之前声明的颜色，清空绘图区
    gl.clear(gl.COLOR_BUFFER_BIT)

    // 初始化程序对象
    initProgram(gl)
    
    class Sky{
      constructor(gl){
        this.gl = gl
        this.children = []
      }
      /** 添加子对象 */
      add(obj){
        obj.gl = this.gl
        this.children.push(obj)
      }
      /** 更新子对象的顶点数据 */
      updateVertices(params){
        this.children.forEach(ele =>{
          ele.updateVertices(params)
        })
      }
      /** 遍历子对象绘图 */
      draw(types){
        this.children.forEach(ele =>{
          ele.init()
          ele.draw(types)
        })
      }
    }
    // 阻止鼠标默认右击事件
    canvas.oncontextmenu = function(e){
      poly.popVertices()
      poly = null
      render()
      return false
    }
    let poly = null,sky = new Sky(gl)
    canvas.addEventListener('click', (event) => {
      if(event.button === 0){
        const {x,y} = getMousePosInWebgl(event, canvas)
        if(poly){
          poly.addVertices(x,y)
          render()
        }else{
          createPloy(x,y)
        }
      }
    })
    canvas.addEventListener('mousemove',(event)=>{
       if(poly){
        const {x,y} = getMousePosInWebgl(event, canvas)
        poly.setVertices(poly.count-1,x,y)
        render()
       }
    })

    function createPloy(x,y){
      poly = new Poly({
        gl:gl,
        vertices:[x,y,x,y],
        size:2
      })
      sky.add(poly)
    }

    function render(){
      gl.clear(gl.COLOR_BUFFER_BIT)
      sky.draw(['POINTS','LINE_STRIP'])
    }

  </script>
</body>

</html>